package com.day12.study.threadpool_demo;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 线程池练习
 *
 * @author Twinkle
 */
public class ThreadPool {

    /**
     * 4.单线程线程池
     */
    public void typeFour() {
        ExecutorService pools = Executors.newSingleThreadExecutor();
        for (int i = 0; i < 5; i++) {
            final int a = i;
            pools.execute(() -> {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(a);
            });
        }
        pools.shutdown();
    }

    /**
     * 3.周期性任务
     */
    public void typeThree() {
        ScheduledExecutorService pools = Executors.newScheduledThreadPool(5);
        pools.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName());
            }
        }, 3, 3, TimeUnit.SECONDS);

    }

    /**
     * 2.定长线程池
     */
    public void typeTwo() {
        ExecutorService pools = Executors.newFixedThreadPool(3);
        for (int i = 0; i < 15; i++) {
            final int a = i;
            pools.execute(() -> {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(a);
            });
        }
        pools.shutdown();
    }

    /**
     * 1.无限大线程池
     */
    public void typeOne() {
        ExecutorService pools = Executors.newCachedThreadPool();
        pools.execute(() -> {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName());
        });
        pools.execute(() -> {
            System.out.println(Thread.currentThread().getName());
        });
        pools.shutdown();
    }

    public static void main(String[] args) {
//        new ThreadPool().typeOne();
//        new ThreadPool().typeTwo();
//        new ThreadPool().typeThree();
//        new ThreadPool().typeFour();
    }
}
